<?php

namespace App\Api\Controller;

use App\Bundle\Cart\CartService;
use Core\Application\Controller;
use Core\Support\Arr;
use Core\Support\Validate;
use G\User\AuthService;

class CartController extends Controller
{
    protected $cartService;

    public function __construct()
    {
        parent::__construct();
        $this->cartService = CartService::getInstance();
    }

    // 购买商品数量+1
    #[Validate('shopId', '缺少参数1')]
    #[Validate('goodsId', '缺少参数2')]
    public function inc()
    {
        $input = $this->getInputJson();

        $this->cartService->setGoods($input, CartService::INC);
        return $this->success();
    }

    // 购买商品数量-1
    #[Validate('shopId', '缺少参数1')]
    #[Validate('goodsId', '缺少参数2')]
    public function dec()
    {
        $input = $this->getInputJson();

        $this->cartService->setGoods($input, CartService::DEC);
        return $this->success();
    }

    // 设置购买商品数量
    #[Validate('shopId', '缺少参数1')]
    #[Validate('goodsId', '缺少参数2')]
    #[Validate('num', '缺少参数3')]
    public function set()
    {
        $input = $this->getInputJson();

        $this->cartService->setGoods($input, CartService::SET);
        return $this->success();
    }

    // 选中/去掉购买商品
    #[Validate('shopId', '缺少参数1')]
    #[Validate('goodsId', '缺少参数2')]
    #[Validate('checked', '缺少参数3')]
    public function checked()
    {
        $input = $this->getInputJson();

        $data = $this->cartService->checked($input);
        return $this->success($data);
    }

    // 将商品从购物车移除
    #[Validate('shopId', '缺少店铺参数')]
    #[Validate('goodsId', '缺少参数2')]
    public function remove()
    {
        $input = $this->getInputJson();

        $this->cartService->remove($input);
        return $this->success();
    }

    // 清空购物车
    #[Validate('shopId', '缺少店铺参数')]
    public function empty()
    {
        $input = $this->getInputJson();

        $this->cartService->empty($input);
        return $this->success();
    }

    // 购物车列表
    #[Validate('shopId', '缺少店铺参数')]
    public function list()
    {
        $uid = AuthService::getInstance()->uid();
        $criteria = $this->getInputAll();

        // 查询列表
        $list = $this->cartService->newQuery()
            ->withGoods()
            ->whereCreator($uid)
            ->whereShopId(Arr::get($criteria, 'shopId'))
            ->orderBy('id', 'desc')
            ->get();

        // 计算已选中商品价格
        $amount = $this->cartService->getAmount($list);
        // 计算已选中商品总数
        $sum = $this->cartService->getNum($list);

        return $this->success([
            'list' => $list,
            'amount' => $amount,
            'sum' => $sum,
        ]);
    }
}
